﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using HtmlDocument = HtmlAgilityPack.HtmlDocument;

namespace HtmlOprate
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly List<string> htmlList = new List<string>();

        SynchronizationContext context = SynchronizationContext.Current;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void openFolderBtn_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            Action<string> action;
            dialog.Description = "请选择Unity Documentation文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    System.Windows.MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
                textList.Items.Clear();
                action = Oprate;
                action.BeginInvoke(dialog.SelectedPath, null, null);
            }
        }

        private void Oprate(string path)
        {
            context.Send((o) =>
            {
                openFolderBtn.IsEnabled = false;
                textList.Items.Clear();
                textList.Items.Add("正在查找文件，请稍后...");
            }, null);

            FindFiles(path);

            context.Send((o) =>
            {
                textList.Items.Clear();
                textList.Items.Add("正在处理，请稍后...");
                progressBar.Maximum = htmlList.Count;
                progressBar.Value = 0;
            }, null);

            for (int i = 0; i < htmlList.Count; i++)
            {
                FileStream stream = new FileStream(htmlList[i], FileMode.Open, FileAccess.ReadWrite);
                HtmlDocument html = new HtmlDocument();
                html.Load(stream, Encoding.UTF8);
                HtmlNode headNode = html.DocumentNode.SelectSingleNode("//head[1]");
                for (int m = 0; m < 6; m++)
                {
                    HtmlNode node = headNode.ChildNodes[m];
                    if (node.Name == "script")
                    {
                        node.Remove();
                        context.Send((o) =>
                        {
                            textList.Items.Add("处理完毕:" + htmlList[i].Replace(path, ""));
                        }, null);
                        break;
                    }
                }
                stream.SetLength(0);
                stream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = Encoding.UTF8.GetBytes(html.DocumentNode.OuterHtml);
                stream.Write(buffer, 0, buffer.Length);
                stream.Close();

                context.Send((o) =>
                {
                    progressBar.Value = i;
                }, null);
            }


            context.Send((o) =>
            {
                openFolderBtn.IsEnabled = true;
            }, null);
        }

        private void FindFiles(string dir)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(dir);
            DirectoryInfo[] dirs = directoryInfo.GetDirectories();
            if (dirs.Length <= 0)
                return;
            foreach (DirectoryInfo item in dirs)
            {
                FindFiles(item.FullName);
            }
            FileInfo[] files = directoryInfo.GetFiles();
            if (files.Length <= 0)
                return;
            foreach (FileInfo file in files)
            {
                if (Path.GetExtension(file.Name) == ".html")
                {
                    htmlList.Add(file.FullName);
                }
            }
        }
    }
}
